#include "wiiuse/wiiuse.h"


#include "WiimoteManager.h"

using namespace MediaCenter;

WiimoteManager::WiimoteManager() : 
	running (false)
{
	running = true;
	wiiusemotes =  wiiuse_init(MAX_WIIMOTES);

	for ( int i = 0; i < MAX_WIIMOTES; i++)
	{
		wiimotes[i] = new Wiimote(wiiusemotes[i]);
	}

	connectionThread = new boost::thread(boost::bind(&WiimoteManager::ThreadFunc, this));
}

WiimoteManager::~WiimoteManager()
{
	Shutdown();
	for (int i = 0; i < MAX_WIIMOTES; i++)
	{
		delete wiimotes[i];
	}
}

void WiimoteManager::ThreadFunc()
{
	while(running)
	{
		int found = wiiuse_find(wiiusemotes, MAX_WIIMOTES, 5);
		if (found > 0)
		{
			int connected = wiiuse_connect(wiiusemotes, MAX_WIIMOTES);

			for (int i = 0; i < connected; i++)
			{
				if (!wiimotes[i]->Connected)
				{
					wiimotes[i]->Connected = true;
					printf("Wiimote connected.\n");
				}
			}
			boost::this_thread::sleep(boost::posix_time::milliseconds(5000));
		}
	}
}

void WiimoteManager::Update()
{
	wiiuse_poll(wiiusemotes, MAX_WIIMOTES);

	for (int i = 0; i < MAX_WIIMOTES; ++i)
	{
		if (wiiusemotes[i]->event == WIIUSE_DISCONNECT ||
			wiiusemotes[i]->event == WIIUSE_UNEXPECTED_DISCONNECT)
		{
			wiimotes[i]->Connected = false;
		}
	}
}

void WiimoteManager::Shutdown()
{
	if (running)
	{
		running = false;
		connectionThread->join();
		wiiuse_cleanup(wiiusemotes, 1);
	}
}
